//
//  CampusQuestionReplyListViewController.m
//  ShowYork
//
//  Created by hxh on 2021/3/29.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "CampusQuestionReplyListViewController.h"

#import "CampusQuestionReplyListCell.h"
#import "CampusQuestionReplyView.h"
@interface CampusQuestionReplyListViewController ()<UITableViewDelegate,UITableViewDataSource,CampusQuestionReplyListCellDelegate>
@property (nonatomic,copy)void(^scrollCallback)(UIScrollView *scrollView);
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)UILabel *noDataLb;
@property (nonatomic,assign)NSInteger pageIndex;
@property (nonatomic,assign)BOOL noData;
@property (nonatomic,strong)NSURLSessionTask *task;
@property (nonatomic,strong)NSNumber *questionId;
@property (nonatomic,strong)NSNumber *targetId;
@property (nonatomic,strong)CampusQuestionAnswerModel *lastModel;

@property (nonatomic,assign)BOOL isTarget;

@end


@implementation CampusQuestionReplyListViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (instancetype)initWithParam:(NSDictionary *)param{
    if (self = [super init]) {
        self.noData = [param[@"status"] boolValue];
        self.questionId = param[@"questionId"];
        [self.dataArray addObjectsFromArray:param[@"list"]];
        self.targetId = param[@"targetId"];
      
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self registNote];
    [self loadTargetQuestionAnswerSource];
    // Do any additional setup after loading the view.
}

- (void)setUI{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    self.noDataLb = [[UILabel alloc]init];
    self.noDataLb.text = @"还没有回答，快来抢沙发～";
    self.noDataLb.textColor = C153;
    self.noDataLb.font = font(12);
    [self.view addSubview:self.noDataLb];
    [self.noDataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view).offset(-100);
        make.centerX.equalTo(self.view);
    }];
    self.noDataLb.hidden = YES;
    
    
    __weak typeof(self)weakSelf = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageIndex++;
        [weakSelf loadDataSource];
    }];

    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    if (self.noData) {
        [footer endRefreshingWithNoMoreData];
    }
    self.tableView.mj_footer = footer;

}


- (void)loadTargetQuestionAnswerSource{
    
    if (self.targetId != nil) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"id"] = self.targetId;
        param[@"userId"] = [RPAppManager getCustomerId];
        param[@"md5"] = [RPAppManager md5StrWithApi:SchoolAnswerDetail];
        [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SchoolAnswerDetail) parames:param success:^(id responseObj) {
            self.lastModel = [CampusQuestionAnswerModel mj_objectWithKeyValues:responseObj[RESPONSE]];
            if (self.lastModel != nil) {
                __block NSInteger index = -1;
                [self.dataArray enumerateObjectsUsingBlock:^(CampusQuestionAnswerModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj.id isEqualToNumber:self.lastModel.id]) {
                        index = idx;
                        *stop = YES;
                    }
                }];
                if (index != -1) {
                    self.isTarget = YES;
                    CampusQuestionAnswerModel *itemModel = self.dataArray[index];
                    itemModel.display = YES;
                    [self.dataArray removeObjectAtIndex:index];
                    [self.dataArray insertObject:itemModel atIndex:0];
                    [self.tableView reloadData];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        itemModel.display = 0;
                        [self.tableView reloadRow:0 inSection:0 withRowAnimation:UITableViewRowAnimationAutomatic];
                    });
                }
            }
        } failure:^(NSError *error) {
            [WHToast showErrorWithMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        }];
    }
}

- (void)loadDataSource{

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.questionId;
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolAnswerList];
    param[@"pageIndex"] = @(self.pageIndex);
    param[@"pageSize"] = @(10);
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SchoolAnswerList) parames:param success:^(id responseObj) {
  
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        
        if (self.pageIndex == 1) {
            self.dataArray = [CampusQuestionAnswerModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[CampusQuestionAnswerModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        CGFloat bottom = self.tableView.mj_insetB;
        if ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            if (self.tableView.mj_footer.cl_height == 44.0f) {
                self.tableView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.tableView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            if (self.tableView.mj_footer.cl_height == 138.0f) {
                self.tableView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.tableView.mj_insetB = 44.0f;
                }
            }
        }
        
        if (!self.isTarget && self.lastModel != nil) {
            __block NSInteger index = -1;
            [self.dataArray enumerateObjectsUsingBlock:^(CampusQuestionAnswerModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.id isEqualToNumber:self.lastModel.id]) {
                    index = idx;
                    *stop = YES;
                }
            }];
            if (index != -1) {
                self.isTarget = YES;
                CampusQuestionAnswerModel *itemModel = self.dataArray[index];
                itemModel.display = YES;
                [self.dataArray removeObjectAtIndex:index];
                [self.dataArray insertObject:itemModel atIndex:0];
                [self.tableView reloadData];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    itemModel.display = 0;
                    [self.tableView reloadRow:0 inSection:0 withRowAnimation:UITableViewRowAnimationAutomatic];
                });
            }
        }
        

        [self.tableView reloadData];
        
    } failure:^(id error) {
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateListSource) name:@"updateCamputAnswerListSource" object:nil];
}
- (void)updateListSource{
    self.pageIndex = 1;
    [self loadDataSource];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    self.noDataLb.hidden = self.dataArray.count > 0;
    self.tableView.mj_footer.hidden = self.dataArray.count == 0;
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CampusQuestionReplyListCell *cell = [CampusQuestionReplyListCell cellWithTableView:tableView];
    [cell setModel:self.dataArray[indexPath.item]];
    cell.delegate = self;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.tableView;
}


- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    self.scrollCallback = callback;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    !self.scrollCallback ?: self.scrollCallback(scrollView);
   
}

#pragma mark - CampusQuestionReplyListCellDelegate
- (void)reportReplyWithItemModel:(CampusQuestionAnswerModel *)itemModel{
    [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":self.navigationController,@"reportId":itemModel.id ,@"reportType":@(0)} completion:nil];
}
- (void)removeReplyWithItemModel:(CampusQuestionAnswerModel *)itemModel{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:DeleteSchoolAnswer];
    param[@"id"] = itemModel.id;
    [SVProgressHUD show];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(DeleteSchoolAnswer) parames:param success:^(id responseObj) {
        
        [WHToast showMessage:@"删除成功" duration:2 finishHandler:nil];
        
        NSInteger index = [self.dataArray indexOfObject:itemModel];
        
        [self.dataArray removeObjectAtIndex:index];
     
        if (self.dataArray.count == 0) {
            [self.tableView reloadData];
        }else{
            [self.tableView deleteRow:index inSection:0 withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        if (self.update) {
            self.update();
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateDetailQuestionAnswerCount" object:nil userInfo:@{@"data":self.questionId,@"status":@(NO)}];
    
    } failure:^(NSError *error) {
        [WHToast showErrorWithMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
- (void)doLikeWithItemModel:(CampusQuestionAnswerModel *)itemModel{
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    [self.task cancel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"type"] = @1;
    param[@"postId"] = itemModel.id;
    param[@"isTourist"] = itemModel.isLike?@1:@2;
    param[@"md5"] = [RPAppManager md5StrWithApi:DoDetailLike];
    param[@"evaluateType"] = @(6);
    self.task = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(DoDetailLike) parames:param success:^(id responseObj) {
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        NSInteger likeNum = itemModel.likeCount.intValue;
        if (itemModel.isLike) {
            likeNum--;
          
        }else{
            likeNum++;
        }
        itemModel.likeCount = @(likeNum);
        itemModel.isLike = !itemModel.isLike;
        [self.tableView reloadData];
    }];
}
- (void)showUserInfoWithItemModel:(CampusQuestionAnswerModel *)itemModel{
   
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"userId":itemModel.userVM.id,@"loadType":@(1)} completion:nil];
}
@end
